//
//  RouColor.swift
//  ONESwift
//
//  Created by wangkun on 2017/6/14.
//  Copyright © 2017年 wangkun. All rights reserved.
//

import UIKit

public func ColorFromRGB(_ R: CGFloat, _ G: CGFloat, _ B: CGFloat, _ A: CGFloat = 1) -> UIColor {
    return UIColor(red: R/255.0, green: G/255.0, blue: B/255.0, alpha: A)
}

extension UIColor {
    /** 十六进制颜色转换*/
    public convenience init(hexString:String){
        
        var cString: String = hexString.trimmingCharacters(in: NSCharacterSet.whitespaces).uppercased()//stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
        
        if (cString.hasPrefix("#")) {
            cString = (cString as NSString).substring(from: 1)
        }
        
        if (cString.count != 6) {
            self.init()
        }else{
            let rString = (cString as NSString).substring(to:2)
            let gString = ((cString as NSString).substring(from:2) as NSString).substring(to: 2)
            let bString = ((cString as NSString).substring(from:4) as NSString).substring(to: 2)
            
            var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
            Scanner(string: rString).scanHexInt32(&r)
            Scanner(string: gString).scanHexInt32(&g)
            Scanner(string: bString).scanHexInt32(&b)
            self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
        }
    }
    
    /** 十六进制颜色转换 ： */
    public convenience init(hex:Int ,alpha : CGFloat = 1){
        let red = (hex >> 16 ) & 0xff
        let green = (hex >> 8 ) & 0xff
        let blue = hex & 0xff
        self.init(red, green, blue, alpha: alpha)!
    }
    
    public convenience init?(_ R : Int , _ G : Int ,_ B : Int , alpha : CGFloat){
        guard  0...255 ~= R else { return nil }
        guard  0...255 ~= G else { return nil }
        guard  0...255 ~= B else { return nil }
        var ap = alpha > 1 ? 1 : alpha
        ap = ap < 0 ? 0 : ap
        self.init(red: CGFloat(R) / 255.0, green: CGFloat(G) / 255.0, blue: CGFloat(B) / 255.0, alpha: ap)
    }
    
}
